package com.dalongxin.work.page;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.TextView;
import com.dalongxin.work.Constants;
import com.dalongxin.work.EventCenter;
import com.dalongxin.work.R;
import com.dalongxin.work.data.Company;
import com.dalongxin.work.data.Contact;
import com.dalongxin.work.data.Department;
import com.dalongxin.work.data.Pay;
import com.dalongxin.work.data.Project;
import com.dalongxin.work.utils.HttpUtil;
import com.dalongxin.work.utils.StatusBarUtil;
import com.dalongxin.work.utils.ToastUtil;
import com.dalongxin.work.view.MyCommonDialog;
import com.dalongxin.work.view.MyCommonEditDialog;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * 新建付款申请
 */
@ContentView(R.layout.activity_dj_new_pay)
public class DjPayNewActivity extends BaseActivity implements View.OnClickListener {

    @ViewInject(R.id.tool_bar)
    private Toolbar toolbar;
    @ViewInject(R.id.title_back)
    private ImageButton titleBack;
    @ViewInject(R.id.title_text)
    private TextView titleText;
    @ViewInject(R.id.submit)
    private TextView submit;

    @ViewInject(R.id.tv_choose_sqr_department)
    private TextView tvChooseSqrDepartment;//选择申请人部门
    @ViewInject(R.id.tv_choose_sqr)
    private TextView tvChooseSqr;//选择申请人
    @ViewInject(R.id.tv_choose_fhr)
    private TextView tvChooseFhr;//选择复核人
    @ViewInject(R.id.tv_choose_cwshr)
    private TextView tvChooseCwshr;//选择财务审核人
    @ViewInject(R.id.tv_choose_pzr)
    private TextView tvChoosePzr;//选择批准人
    @ViewInject(R.id.tv_choose_company)
    private TextView tvChooseCompany;//选择公司
    @ViewInject(R.id.tv_choose_sqrq)
    private TextView tvChooseSqrq;//申请日期
    @ViewInject(R.id.tv_choose_xm)
    private TextView tvChooseXm;//选择项目

    @ViewInject(R.id.et_lxrxm)
    private EditText etLxrxm;//联系人姓名
    @ViewInject(R.id.et_lxrdh)
    private EditText etLxrdh;//联系人电话
    @ViewInject(R.id.et_fkyt)
    private EditText etFkyt;//付款用途
    @ViewInject(R.id.et_skzh)
    private EditText etSkzh;//收款账号
    @ViewInject(R.id.et_skdwkhh)
    private EditText etSkdwkhh;//收款单位开户行
    @ViewInject(R.id.et_skdwmc)
    private EditText etSkdwmc;//收款单位名称
    @ViewInject(R.id.et_bz)
    private EditText etBz;//备注
    @ViewInject(R.id.et_qkje)
    private EditText etQkje;//请款金额
    @ViewInject(R.id.et_qkjedx)
    private EditText etQkjedx;//请款金额大写
    @ViewInject(R.id.btn_operate)
    private Button btnOperate;

    public static final int REQ_CHOOSE_DEPARTMENT = 1001;
    public static final int REQ_CHOOSE_CONTACT_SQR = 1002;
    public static final int REQ_CHOOSE_CONTACT_FHR = 1003;
    public static final int REQ_CHOOSE_CONTACT_CWSHR = 1004;
    public static final int REQ_CHOOSE_CONTACT_PZR = 1005;
    public static final int REQ_CHOOSE_COMPANY = 1006;
    public static final int REQ_CHOOSE_XM = 1007;

    public Calendar calendar;

    private Department chooseDepartment;
    private Contact chooseSqr;
    private Contact chooseFhr;
    private Contact chooseCwshr;
    private Contact choosePzr;
    private Company chooseCompany;
    private Project chooseProject;
    private String sqrq;

    private String lxrxm;
    private String lxrdh;
    private String fkyt;
    private String skzh;
    private String skdwkhh;
    private String skdwmc;
    private String bz;
    private String qkje;
    private String qkjedx;

    private MyCommonDialog commonDialog;
    private MyCommonEditDialog commonEditDialog;

    public static final String IS_EDIT = "is_edit";
    private int isEdit = 0;// 0新建 1查看
    private Pay bean;
    private boolean canEdit = false;
    private int editState = 0;//0查看状态 1修改状态

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        //this.setSupportActionBar(toolbar);//这样menu才能显示出来【自定义toolbar的话 这个不要设置】
        //getSupportActionBar().setDisplayShowTitleEnabled(false);//去掉默认title的显示
        StatusBarUtil.setPaddingSmart(this, toolbar);
        StatusBarUtil.darkMode(this, false);
        isEdit = getIntent().getIntExtra(IS_EDIT, 0);
        if(isEdit == 0) {
            titleText.setText("新建付款申请");
            submit.setText("提交");
            switchToEditState();
        }else {
            Bundle bundle = getIntent().getBundleExtra("bundle");
            bean = (Pay) bundle.getSerializable("BEAN");
            if(bean == null) {
                finish();
                return;
            }
            if(bean.getCreateId() == getDefaultAccount().getId() && bean.getStatus() == 0) {
                canEdit = true;
                titleText.setText("查看付款申请");
                submit.setText("修改");
            }else {
                titleText.setText("查看付款申请");
                submit.setVisibility(View.GONE);
            }
            fillDataToPage(bean);
            btnOperate.setVisibility(showOperateBtn(bean) ? View.VISIBLE : View.GONE);
            btnOperate.setOnClickListener(this);
        }
        titleBack.setOnClickListener(this);
        submit.setOnClickListener(this);

        calendar = Calendar.getInstance();
    }

    private boolean showOperateBtn(Pay bean) {
        if(bean.getStatus() == 0 && bean.getApproveId1() == getDefaultAccount().getId()) {
            return true;
        }
        if(bean.getStatus() == 1 && bean.getApproveId2() == getDefaultAccount().getId()) {
            return true;
        }
        if(bean.getStatus() == 2 && bean.getApproveId3() == getDefaultAccount().getId()) {
            return true;
        }
        return false;
    }

    private void fillDataToPage(Pay bean) {
        chooseDepartment = new Department();
        chooseDepartment.setDepartmentId(bean.getDepartmentId());
        chooseDepartment.setDepartmentName(bean.getDepartmentName());
        chooseCompany = new Company();
        chooseCompany.setId(bean.getCompanyId());
        chooseCompany.setName(bean.getCompanyName());
        chooseSqr = new Contact();
        chooseSqr.setId(bean.getApplyUserId());
        chooseSqr.setUserName(bean.getApplyUserName());
        chooseFhr = new Contact();
        chooseFhr.setId(bean.getApplyUserId());
        chooseFhr.setUserName(bean.getApplyUserName());
        chooseCwshr = new Contact();
        chooseCwshr.setId(bean.getApplyUserId());
        chooseCwshr.setUserName(bean.getApplyUserName());
        choosePzr = new Contact();
        choosePzr.setId(bean.getApproveId2());
        choosePzr.setUserName(bean.getApproveName2());
        chooseProject = new Project();
        chooseProject.setId(bean.getProjectId());
        chooseProject.setName(bean.getProjectName());

        lxrxm = bean.getContactUserName();
        lxrdh = bean.getContactUserPhone();
        sqrq = bean.getFillDate();
        fkyt = bean.getReason();
        skzh = bean.getReceiveAccount();
        skdwkhh = bean.getReceiveBank();
        skdwmc = bean.getReceiveCompany();
        bz = bean.getRemark();
        qkje = String.valueOf(bean.getTotalFee());
        qkjedx = bean.getUpperCaseFee();

        tvChooseSqrDepartment.setText(chooseDepartment.getDepartmentName());
        tvChooseSqr.setText(chooseSqr.getUserName());
        tvChooseFhr.setText(chooseFhr.getUserName());
        tvChooseCwshr.setText(chooseCwshr.getUserName());
        tvChoosePzr.setText(choosePzr.getUserName());
        tvChooseCompany.setText(chooseCompany.getName());
        tvChooseSqrq.setText(sqrq);
        tvChooseXm.setText(chooseProject.getName());

        etLxrxm.setText(lxrxm);
        etLxrdh.setText(lxrdh);
        etFkyt.setText(fkyt);
        etSkzh.setText(skzh);
        etSkdwkhh.setText(skdwkhh);
        etSkdwmc.setText(skdwmc);
        etBz.setText(bz);
        etQkje.setText(qkje);
        etQkjedx.setText(qkjedx);

        switchToViewState();//默认查看状态
    }

    private void switchToEditState() {
        tvChooseSqrDepartment.setOnClickListener(this);
        tvChooseSqr.setOnClickListener(this);
        tvChooseFhr.setOnClickListener(this);
        tvChooseCwshr.setOnClickListener(this);
        tvChoosePzr.setOnClickListener(this);
        tvChooseCompany.setOnClickListener(this);
        tvChooseSqrq.setOnClickListener(this);
        tvChooseXm.setOnClickListener(this);
        etLxrxm.setEnabled(true);
        etLxrdh.setEnabled(true);
        etFkyt.setEnabled(true);
        etSkzh.setEnabled(true);
        etSkdwkhh.setEnabled(true);
        etSkdwmc.setEnabled(true);
        etBz.setEnabled(true);
        etQkje.setEnabled(true);
        etQkjedx.setEnabled(true);
    }

    private void switchToViewState() {
        tvChooseSqrDepartment.setOnClickListener(null);
        tvChooseSqr.setOnClickListener(null);
        tvChooseFhr.setOnClickListener(null);
        tvChooseCwshr.setOnClickListener(null);
        tvChoosePzr.setOnClickListener(null);
        tvChooseCompany.setOnClickListener(null);
        tvChooseSqrq.setOnClickListener(null);
        tvChooseXm.setOnClickListener(null);
        etLxrxm.setEnabled(false);
        etLxrdh.setEnabled(false);
        etFkyt.setEnabled(false);
        etSkzh.setEnabled(false);
        etSkdwkhh.setEnabled(false);
        etSkdwmc.setEnabled(false);
        etBz.setEnabled(false);
        etQkje.setEnabled(false);
        etQkjedx.setEnabled(false);
    }

    private void submitPay() {
        showLoading();
        Map<String, String> params = new HashMap<>();
        params.put("applyDepartmentId", String.valueOf(chooseDepartment.getDepartmentId()));
        params.put("applyUserId",String.valueOf(chooseSqr.getId()));
        params.put("approveId1",String.valueOf(chooseFhr.getId()));
        params.put("approveId2",String.valueOf(chooseCwshr.getId()));
        params.put("approveId3",String.valueOf(choosePzr.getId()));
        params.put("companyId", String.valueOf(chooseCompany.getId()));
        params.put("contactUserName", lxrxm);
        params.put("contactUserPhone", lxrdh);
        params.put("fillDate", sqrq);
        params.put("projectId", String.valueOf(chooseProject.getId()));
        params.put("reason", fkyt);
        params.put("receiveAccount", skzh);
        params.put("receiveBank", skdwkhh);
        params.put("receiveCompany", skdwmc);
        params.put("remark", bz);
        params.put("totalFee", qkje);
        params.put("upperCaseFee", qkjedx);
        if(canEdit) {
            params.put("id", String.valueOf(bean.getId()));
        }else {
            params.put("id", String.valueOf(0));
        }
        HttpUtil.getInstance().post(true, Constants.url_savePay, params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject response) {
                LogUtil.e("response=" + response);
                if (response.optInt("ret") == 0) {
                    ToastUtil.showShort("提交成功");
                    EventBus.getDefault().post(EventCenter.call(EventCenter.PAY_REFRESH));
                } else {
                    ToastUtil.showShort(response.optString("msg"));
                }
                finish();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ToastUtil.showShort("服务器返回失败");
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                hideLoading();
            }
        });
    }

    private void submitApprove(String content, int result) {
        showLoading();
        Map<String, String> params = new HashMap<>();
        params.put("msg", content);
        params.put("result", String.valueOf(result));
        params.put("id", String.valueOf(bean.getId()));
        HttpUtil.getInstance().post(true, Constants.url_approvePay, params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject response) {
                commonEditDialog.dismiss();
                LogUtil.e("response=" + response);
                if (response.optInt("ret") == 0) {
                    ToastUtil.showShort("提交成功");
                    EventBus.getDefault().post(EventCenter.call(EventCenter.PAY_REFRESH));
                } else {
                    ToastUtil.showShort(response.optString("msg"));
                }
                finish();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ToastUtil.showShort("服务器返回失败");
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                hideLoading();
            }
        });
    }

    private void preSubmit() {
        if(chooseDepartment == null) {
            ToastUtil.showShort("请选择申请人部门");
            return;
        }
        if(chooseSqr == null) {
            ToastUtil.showShort("请选择申请人");
            return;
        }
        if(chooseFhr == null) {
            ToastUtil.showShort("请选择复核人");
            return;
        }
        if(tvChooseCwshr == null) {
            ToastUtil.showShort("请选择财务审核人");
            return;
        }
        if(choosePzr == null) {
            ToastUtil.showShort("请选择批准人");
            return;
        }
        if(chooseCompany == null) {
            ToastUtil.showShort("请选择公司");
            return;
        }
        if(TextUtils.isEmpty(sqrq)) {
            ToastUtil.showShort("请选择申请日期");
            return;
        }
        if(chooseProject == null) {
            ToastUtil.showShort("请选择项目");
            return;
        }
        lxrxm = etLxrxm.getText().toString();
        if(TextUtils.isEmpty(lxrxm)) {
            ToastUtil.showShort("请填写联系人姓名");
            return;
        }
        lxrdh = etLxrdh.getText().toString();
        if(TextUtils.isEmpty(lxrdh)) {
            ToastUtil.showShort("请填写联系人电话");
            return;
        }
        fkyt = etFkyt.getText().toString();
        if(TextUtils.isEmpty(fkyt)) {
            ToastUtil.showShort("请填写付款用途");
            return;
        }
        skzh = etSkzh.getText().toString();
        if(TextUtils.isEmpty(skzh)) {
            ToastUtil.showShort("请填写收款账号");
            return;
        }
        skdwkhh = etSkdwkhh.getText().toString();
        if(TextUtils.isEmpty(skdwkhh)) {
            ToastUtil.showShort("请填写收款单位开户行");
            return;
        }
        skdwmc = etSkdwmc.getText().toString();
        if(TextUtils.isEmpty(skdwmc)) {
            ToastUtil.showShort("请填写收款单位名称");
            return;
        }
        bz = etBz.getText().toString();
        if(TextUtils.isEmpty(bz)) {
            bz = "";
        }
        qkje = etQkje.getText().toString();
        if(TextUtils.isEmpty(qkje)) {
            ToastUtil.showShort("请填写请款金额");
            return;
        }
        qkjedx = etQkjedx.getText().toString();
        if(TextUtils.isEmpty(qkjedx)) {
            ToastUtil.showShort("请填写请款金额大写");
            return;
        }
        commonDialog = new MyCommonDialog(this, "提示消息", "确定提交吗？", "检查一下","提交");
        commonDialog.setOkListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (commonDialog != null && commonDialog.isShowing())
                    commonDialog.dismiss();
                submitPay();
            }
        });
        commonDialog.setCancelListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (commonDialog != null && commonDialog.isShowing())
                    commonDialog.dismiss();
            }
        });
        commonDialog.show();
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.submit:
                if(isEdit == 0) {
                    preSubmit();
                }else {
                    if(canEdit) {
                        if (editState == 0) {
                            editState = 1;
                            titleText.setText("修改付款申请");
                            submit.setText("提交");
                            switchToEditState();
                        } else {
                            editState = 0;
                            titleText.setText("修改付款申请");
                            preSubmit();
                        }
                    }
                }
                break;
            case R.id.tv_choose_sqrq:
                int year2 = calendar.get(Calendar.YEAR);
                int month2 = (calendar.get(Calendar.MONTH))+1;
                int day_of_month2 = calendar.get(Calendar.DAY_OF_MONTH);
                new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
                        sqrq = String.format("%d-%d-%d",i,i1+1,i2);
                        tvChooseSqrq.setText(sqrq);
                        tvChooseSqrq.setTextColor(getResources().getColor(R.color.black));
                    }
                },year2, month2, day_of_month2).show();
                break;
            case R.id.tv_choose_sqr_department:
                intent = new Intent(this, DepartmentListActivity.class);
                startActivityForResult(intent, REQ_CHOOSE_DEPARTMENT);
                break;
            case R.id.tv_choose_sqr:
                intent = new Intent(this, ContactListActivity.class);
                startActivityForResult(intent, REQ_CHOOSE_CONTACT_SQR);
                break;
            case R.id.tv_choose_fhr:
                intent = new Intent(this, ContactListActivity.class);
                startActivityForResult(intent, REQ_CHOOSE_CONTACT_FHR);
                break;
            case R.id.tv_choose_cwshr:
                intent = new Intent(this, ContactListActivity.class);
                startActivityForResult(intent, REQ_CHOOSE_CONTACT_CWSHR);
                break;
            case R.id.tv_choose_pzr:
                intent = new Intent(this, ContactListActivity.class);
                startActivityForResult(intent, REQ_CHOOSE_CONTACT_PZR);
                break;
            case R.id.tv_choose_company:
                intent = new Intent(this, CompanyListActivity.class);
                startActivityForResult(intent, REQ_CHOOSE_COMPANY);
                break;
            case R.id.tv_choose_xm:
                intent = new Intent(this, ProjectListActivity.class);
                startActivityForResult(intent, REQ_CHOOSE_XM);
                break;
            case R.id.btn_operate:
                final MyCommonEditDialog.Builder builder2 = new MyCommonEditDialog.Builder(this);
                commonEditDialog = builder2.view(R.layout.dialog_approve).widthdp(300).heightdp(320).style(R.style.MyDialogStyle)
                        .addViewOnclick(R.id.cancel, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                commonEditDialog.dismiss();
                            }
                        }).addViewOnclick(R.id.ok, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                EditText etSpyj = (EditText)builder2.findViewById(R.id.et_spyj);
                                String spyj = etSpyj.getText().toString();
                                if(TextUtils.isEmpty(spyj)) {
                                    spyj = "";
                                }
                                RadioButton yes = (RadioButton)builder2.findViewById(R.id.radio_result_yes);
                                submitApprove(spyj, yes.isChecked() ? 0 : 1);
                            }
                        }).build();
                commonEditDialog.show();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data == null)return;
        if(resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQ_CHOOSE_DEPARTMENT:
                    chooseDepartment = (Department)data.getSerializableExtra(DepartmentListActivity.DATA_CHOOSE_DEPARTMENT);
                    tvChooseSqrDepartment.setText(chooseDepartment.getDepartmentName());
                    tvChooseSqrDepartment.setTextColor(getResources().getColor(R.color.black));
                    break;
                case REQ_CHOOSE_CONTACT_SQR:
                    chooseSqr = (Contact)data.getSerializableExtra(ContactListActivity.DATA_CHOOSE_CONTACT);
                    tvChooseSqr.setText(chooseSqr.getUserName());
                    tvChooseSqr.setTextColor(getResources().getColor(R.color.black));
                    break;
                case REQ_CHOOSE_CONTACT_FHR:
                    chooseFhr = (Contact)data.getSerializableExtra(ContactListActivity.DATA_CHOOSE_CONTACT);
                    tvChooseFhr.setText(chooseFhr.getUserName());
                    tvChooseFhr.setTextColor(getResources().getColor(R.color.black));
                    break;
                case REQ_CHOOSE_CONTACT_CWSHR:
                    chooseCwshr = (Contact)data.getSerializableExtra(ContactListActivity.DATA_CHOOSE_CONTACT);
                    tvChooseCwshr.setText(chooseCwshr.getUserName());
                    tvChooseCwshr.setTextColor(getResources().getColor(R.color.black));
                    break;
                case REQ_CHOOSE_CONTACT_PZR:
                    choosePzr = (Contact)data.getSerializableExtra(ContactListActivity.DATA_CHOOSE_CONTACT);
                    tvChoosePzr.setText(choosePzr.getUserName());
                    tvChoosePzr.setTextColor(getResources().getColor(R.color.black));
                    break;
                case REQ_CHOOSE_COMPANY:
                    chooseCompany = (Company)data.getSerializableExtra(CompanyListActivity.DATA_CHOOSE_COMPANY);
                    tvChooseCompany.setText(chooseCompany.getName());
                    tvChooseCompany.setTextColor(getResources().getColor(R.color.black));
                    break;
                case REQ_CHOOSE_XM:
                    chooseProject = (Project)data.getSerializableExtra(ProjectListActivity.DATA_CHOOSE_XM);
                    tvChooseXm.setText(chooseProject.getName());
                    tvChooseXm.setTextColor(getResources().getColor(R.color.black));
                    break;
            }
        }
    }
}
